package com.example.parking.service.impl;

import com.example.parking.dto.LoginFrom;
import com.example.parking.dto.Result;
import com.example.parking.entity.CarInfo;
import com.example.parking.entity.User;
import com.example.parking.mapper.UserMapper;
import com.example.parking.service.ILoginService;
import com.example.parking.service.IUserService;
import com.example.parking.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.utility.RandomString;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;


@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IUserService userService;


    /**
     * 登录(注册)操作
     * @return
     */
    @Override
    public Result login(LoginFrom loginFrom) {
        String phone = loginFrom.getPhone();
        String password = loginFrom.getPassword();
        //检验手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号不合法");
        }
        //根据手机号查询数据库
        User user = userMapper.getByPhone(phone);
        //如果用户不存在，就自动创建
        if (user == null) {
            //创建新用户 保存手机号和密码
            User createUser = new User();
            createUser.setPhone(phone);
            createUser.setPassword(password);
            createUser.setUsername(RandomString.make(6));
            userService.save(createUser);
            user = createUser;
        }
        //如果用户存在 去数据库调取密码验证
        else if (!user.getPassword().equals(password)) {
            return Result.fail("密码错误");
        }
        //返回当前登录用户的id
        return Result.successData(user.getUserId());
    }
}
